package org.litemall.netty.config;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.litemall.netty.nettyDoman.AdminChannel;
import org.litemall.netty.nettyDoman.SocketMessage;
import org.litemall.netty.nettyDoman.UserChannel;
import org.litemall.netty.service.ChannelSupervise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author Lizr
 * @Description websocket 链接处理器
 * @CreateTime 2021-10-28 上午 10:54
 **/
@ChannelHandler.Sharable
@Component
public class WebsocketMessageHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(WebsocketMessageHandler.class);

    private WebSocketServerHandshaker handshaker;

    /**
     * 空闲次数 超过后 关闭socket
     */
    int closeCount = 3;


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent)evt;
        AdminChannel adminChannel = ChannelSupervise.AdminCannelMap.get(ctx.channel().id().asShortText());
        UserChannel userChannel = null;
        // 空闲次数
        Integer count = 0;
        if(adminChannel == null){
            userChannel = ChannelSupervise.UserCannelMap.get(ctx.channel().id().asShortText());
        }
        String eventType = null;

        switch (event.state()){
            case READER_IDLE:
                eventType = "读空闲";
                if(adminChannel == null){
                    count = userChannel.getReadFreeCount().incrementAndGet();
                }else{
                    count = adminChannel.getReadFreeCount().incrementAndGet();
                }

                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                if(adminChannel == null){
                    count = userChannel.getReadFreeCount().incrementAndGet();
                }else{
                    count = adminChannel.getReadFreeCount().incrementAndGet();
                }
                // 不处理
                break;
            case ALL_IDLE:
                eventType ="读写空闲";
                // 不处理
                break;
        }
        // 当前socket空闲次数加一，如果到达一定次数 则关闭当前socket
        if(count >= closeCount){
            if(adminChannel == null){
                logger.info("当前连接socket: [{}], 用户ID: [{}], {}次数已到达 {}次 关闭当前socket", userChannel.getChannelId(), userChannel.getUserId(), eventType ,count);
                userChannel.sendTestMessage(SocketMessage.sendClonseMessage().toString());
                ChannelSupervise.removeUserChannel(userChannel.getChannel());
                userChannel.getChannel().close();
                // logger.debug("断开时间:" + LocalDateTime.now());
            }else{
                logger.info("当前连接socket: [{}], 管理员ID: [{}], {}次数已到达 {}次 关闭当前socket", adminChannel.getChannelId(), adminChannel.getAdminId(), eventType ,count);
                adminChannel.sendTestMessage(SocketMessage.sendClonseMessage().toString());
                ChannelSupervise.removeAdminChannel(adminChannel.getChannel());
                adminChannel.getChannel().close();
                // logger.debug("断开时间:" + LocalDateTime.now());
            }

        }else{
            super.userEventTriggered(ctx, evt);
        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        if (msg instanceof FullHttpRequest){
            //以http请求形式接入，但是走的是websocket
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }else if (msg instanceof  WebSocketFrame){
            //处理websocket客户端的消息
            handlerWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        // logger.debug("客户端加入连接："+ctx.channel());
        // ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        // logger.debug("客户端断开连接："+ctx.channel());
        ChannelSupervise.removeAdminChannel(ctx.channel());
        ChannelSupervise.removeUserChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    // 处理 接受文本信息
    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            logger.debug("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        try {
            logger.info("服务端收到消息: " + request);
            JSONObject json = JSONObject.parseObject(request);
            if(!json.containsKey("userId") && !json.containsKey("userType")){
                throw new RuntimeException("拒绝链接");
            }

            Integer userType = json.getInteger("userType");
            Integer userId = json.getInteger("userId");
            if(userType.equals(1)){
                // 链接类型为普通用户
                // 保存连接
                if(ChannelSupervise.checkUserContainsKey(ctx.channel()) == false){
                    logger.debug("连接时间:" + LocalDateTime.now());
                    // 链接类型为用户
                    UserChannel userChannel = new UserChannel();
                    userChannel.setReadFreeCount(new AtomicInteger(0));
                    userChannel.setUserId(userId);
                    userChannel.setChannel(ctx.channel());
                    userChannel.setChannelId(ctx.channel().id().asShortText());
                    ChannelSupervise.addUserChannel(userChannel);
                    TextWebSocketFrame t = new TextWebSocketFrame(SocketMessage.sendJoinMessage().toString());
                    ctx.channel().writeAndFlush(t);
                }
            }else if(userType.equals(2)){
                // 保存连接
                if(ChannelSupervise.checkAdminContainsKey(ctx.channel()) == false){
                    // 链接类型为管理员用户
                    AdminChannel adminChannel = new AdminChannel();
                    adminChannel.setReadFreeCount(new AtomicInteger(0));
                    adminChannel.setAdminId(userId);
                    adminChannel.setChannel(ctx.channel());
                    adminChannel.setChannelId(ctx.channel().id().asShortText());
                    ChannelSupervise.addAdminChannel(adminChannel);
                    ctx.channel().writeAndFlush("管理员您好！！！");
                }
            }
            // TextWebSocketFrame tws = new TextWebSocketFrame();
            // 群发
            // ChannelSupervise.send2All(tws);
            // 返回【谁发的发给谁】
            // ctx.channel().writeAndFlush(tws);

        }catch(Exception e){
//            logger.error("一个socket链接被拒绝,原因 接收消息内容不包含 userId 和 userType");
//            String json = null; //JSONObject.toJSONString(Result.error("消息内容未包含指定数据", 0, null));
//            TextWebSocketFrame t = new TextWebSocketFrame(json);
//            ctx.writeAndFlush(t);
            // 不接受连接消息， 返回检测消息
            TextWebSocketFrame tws = new TextWebSocketFrame(SocketMessage.sendBeatMessage().toString());
            ctx.channel().writeAndFlush(tws);

        }

    }
    /**
     * 唯一的一次http请求，用于创建websocket
     * */
    private void handleHttpRequest(ChannelHandlerContext ctx,
                                   FullHttpRequest req) {
        //要求Upgrade为websocket，过滤掉get/Post
        if (!req.decoderResult().isSuccess()
                || (!"websocket".equals(req.headers().get("Upgrade")))) {
            //若不是websocket方式，则创建BAD_REQUEST的req，返回给客户端
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
            return;
        }
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                "ws://127.0.0.1:7777/websocket", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }
    /**
     * 拒绝不合法的请求，并返回错误信息
     * */
    private static void sendHttpResponse(ChannelHandlerContext ctx,
                                         FullHttpRequest req, DefaultFullHttpResponse res) {
        // 返回应答给客户端
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(),
                    CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
        }
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        // 如果是非Keep-Alive，关闭连接
        if ( res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
